package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService  {
@Autowired
private DeptService deptService;

@Autowired
private EmpMapper empMapper;

@Autowired
private EmpExprServiceImpl empExprService;


    @Override
    public PageResult page(EmpQueryParam param) {
        LambdaQueryWrapper<Emp> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(param.getName()!=null&& !param.getName().isEmpty(),Emp::getName,param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());

        IPage<Emp> page = new Page<>(param.getPage(), param.getPageSize());
        IPage<Emp> page1 = page(page, queryWrapper);
        List<Emp> records = page1.getRecords();

        records.forEach(emp -> {
            Dept byId = deptService.getById(emp.getDeptId());
            if (byId != null) {
                emp.setDeptName(byId.getName());
            }
        });
        return new PageResult(page1.getTotal(), records);
    }

    @Override
    public void insert(Emp emp) {
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        save(emp);

        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(e->{
            e.setEmpId(emp.getId());
        });
    }

    @Override
    public void delete(List<Integer> ids) {
        removeBatchByIds(ids);
        LambdaQueryWrapper<EmpExpr> empExprWrapper =new  LambdaQueryWrapper();
        empExprWrapper.in(EmpExpr::getEmpId, ids);
        empExprService.remove(empExprWrapper);


    }

    @Override
    public void updata(Emp emp) {
        updateById(emp);
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        empExprService.saveBatch(emp.getExprList());


    }

    @Override
    public Emp getById1(Integer id) {
        Emp byId = getById(id);
        List<EmpExpr> list = empExprService.lambdaQuery().eq(EmpExpr::getEmpId,id).list();
        byId.setExprList(list);
        return byId;
    }


}
